import * as fs from 'fs';
import { APIError } from './plugin/restful';
import * as crypto from 'crypto';
import config from './config';
// 放置一些通用的封装
// 在不同的地方出现两次及以上的封装应该放于此处

export const readTextFile = (path: string) => {
  return new Promise((resolve, reject) => {
    fs.readFile(path, { encoding: 'utf-8' }, (err, data) => {
      if (err) return reject(err);
      resolve(data);
    });
  });
};

// message仅返回第一个错误
export const generateParamsError = (code: string, messages: any[]) => {
  const idxs = Object.keys(messages[0]);
  const message = messages[0][idxs[0]];
  return new APIError(code, message);
};

export const md5 = (...keys: string[]) => {
  const hash = crypto.createHash('md5');
  keys.forEach(key => hash.update(key));
  return hash.digest('hex');
};

export const md5WithSecret = (password: string) => md5(config.passwordSecret, password);
